<template>
  <el-space>
    <span>{{ scope?.column?.label }}</span>

    <el-popover
      placement="bottom"
      :width="320"
      trigger="click"
      :visible="visible"
      popper-class="date-range-filter-popper"
      ref="popoverRef"
    >
      <template #reference>
        <el-button text size="small" :icon="Filter" circle @click.stop="visible = !visible" />
      </template>

      <template #default>
        <el-date-picker
          v-bind="option"
          v-model="value"
          placeholder="请选择"
          style="width: 100%; box-sizing: border-box"
          popper-class="date-range-filter-popper"
        />
        <div class="flex justify-end mt-2">
          <el-space>
            <el-button type="default" size="small" @click="handleReset()">重置</el-button>
            <el-button type="primary" size="small" @click="handleQuery()">查询</el-button>
          </el-space>
        </div>
      </template>
    </el-popover>
  </el-space>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Filter } from '@element-plus/icons-vue'

defineOptions({
  name: 'DateRangeFilter'
})

const props = defineProps<{
  scope: {
    type: Object
  }
  option: {
    type: Object
  }
}>()

const emit = defineEmits(['query', 'reset'])

const value = ref([])
const visible = ref(false)
const popoverRef = ref(null)

const handleQuery = () => {
  emit('query', {
    property: props.scope?.column?.property,
    value: value.value
  })
  visible.value = false
}

const handleReset = () => {
  value.value = []
  emit('reset', {
    property: props.scope?.column?.property,
    value: []
  })
}

onMounted(() => {
  document.addEventListener('click', (e) => {
    visible.value = false
  })

  document.querySelectorAll('.date-range-filter-popper')?.forEach((popper) => {
    popper.addEventListener('click', (e) => {
      e.preventDefault()
      e.stopPropagation()
    })
  })
})
</script>
